<template>
    <div class="app-container">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox searchForm" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                label-width="58px">
                <el-form-item label="医院" prop="hospital" clearable>
                    <department :isHospital="true" :isdepat="false" @refreshData="refreshData" deptWidth="200px"
                        ref="department"></department>
                </el-form-item>
                <el-form-item label="专病名称" prop="diseaseClassifyName">
                    <el-input v-model="queryParams.diseaseClassifyName" placeholder="请输入专病名称" clearable style="width: 160px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>

                <el-form-item label="状态" prop="status" clearable>
                    <el-select v-model="queryParams.status" placeholder="状态" clearable filterable style="width: 160px">
                        <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="dateRange" style="width:240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5" v-if="isAdmin || isPlatform">
                        <!--                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"-->
                        <!--                            v-hasPermi="['system:classify:add']">新增</el-button>-->
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="classifyList" @selection-change="handleSelectionChange" border>
                    <!--                <el-table-column type="selection" width="50" align="center" />-->
                    <el-table-column sortable label="专病编号" align="center" prop="diseaseClassifyId" width="100" />
                  
                    <el-table-column sortable label="专病名称" align="center" prop="diseaseClassifyName"
                        :show-overflow-tooltip="true" width="150" />
                    <!-- <el-table-column label="医院" align="center" prop="hospitalName" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <departTag :options="deptNameLists" :value="scope.row.hospitalId" />
                        </template>
                    </el-table-column>
                    <el-table-column label="科室" align="center" prop="deptName" :show-overflow-tooltip="true" width="150">
                        <template slot-scope="scope">
                            <departTag :options="deptNameLists" :value="scope.row.deptId" />
                        </template>
                    </el-table-column> -->
                    <el-table-column sortable label="分型" align="center" prop="diseaseType" :show-overflow-tooltip="true" />
                    <el-table-column sortable label="分期" align="center" prop="diseaseSerialization"
                        :show-overflow-tooltip="true" />
                    <el-table-column sortable label="创建时间" align="center" prop="createTime" width="160">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
                    <el-table-column sortable label="状态" align="center" key="status" width="100">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                                v-hasPermi="['system:classify:edit']" @change="handleStatusChange(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <!--                    <el-table-column label="操作" align="center" fixed="right" width="160"-->
                    <!--                        class-name="small-padding fixed-width">-->
                    <!--                        <template slot-scope="scope">-->
                    <!--                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"-->
                    <!--                                v-hasPermi="['system:classify:edit']">修改</el-button>-->
                    <!--                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
                    <!--                                v-hasPermi="['system:classify:remove']">删除</el-button>-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <el-table-column label="操作" align="center" fixed="right" width="160"
                        class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-if="isAdmin">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-if="isPlatform" :disabled="(scope.row.hospitalId != hospital.deptId)">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-if="isAdmin">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </div>

        </el-row>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
            :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="专病名称" prop="diseaseClassifyName">
                            <el-input v-model="form.diseaseClassifyName" :disabled="inputDisabled" placeholder="请输入专病名称"
                                clearable style="width: 240px" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="专病分类" prop="diseaseClassifyName">
                            <el-input v-model="form.diseaseClassifyName" placeholder="请输入专病分类" clearable />
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="使用科室" prop="deptId" v-if="open">
                            <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="form.hospitalId" :Optiohospitals="true"
                                :deptIds="form.deptId" :isdisabled="false" deptWidth="240px"></department>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="分型">
                            <el-input v-model="mform.fx" placeholder="请输入分型,点击添加" style="width: 240px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2" :offset="2">
                        <el-button type="primary" size="mini" @click="addFX">添加</el-button>
                    </el-col>
                </el-row>
                <el-row style="margin:0 auto 22px 80px" v-show="fxz.length > 0">
                    <el-tag :key="tag" v-for="tag in fxz" closable :disable-transitions="false"
                        @close="fxzHandleClose(tag)">
                        {{ tag }}
                    </el-tag>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="分期">
                            <el-input v-model="mform.fq" placeholder="请输入分期,点击添加" style="width: 240px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2" :offset="2">
                        <el-button type="primary" size="mini" @click="addFQ">添加</el-button>
                    </el-col>
                </el-row>
                <el-row style="margin:0 auto 22px 80px" v-show="fqz.length > 0">
                    <el-tag :key="tag" v-for="tag in fqz" closable :disable-transitions="false"
                        @close="fqzHandleClose(tag)">
                        {{ tag }}
                    </el-tag>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                                    :label="dict.value">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-form-item label="是否用于色斑平台" label-width="140px">
                        <el-radio-group v-model="form.platformType">
                          <el-radio v-for="dict in stainArr" :key="dict.value" :label="dict.value">{{ dict.label
                          }}</el-radio>
                        </el-radio-group>
                      </el-form-item>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 专病导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的专病数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 引入平台模板 -->
        <el-dialog :title="platformTitle" :visible.sync="platformTempDialogVisible" v-dialogDrag width="90%"
            :close-on-click-modal="false">
            <platformTemp v-if="platformTempDialogVisible" @closeplatformTempDialogVisible="closeplatformTempDialogVisible"
                type="3" @refresh="getList">
            </platformTemp>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import department from "@/views/components/department/index.vue";
import departTag from "@/views/components/department/departTag.vue";
import platformTemp from "@/views/components/platformTemp/classifyTemp.vue";
import {
    listClassify,
    getClassify,
    delClassify,
    addClassify,
    updateClassify,
    changeClassifyStatus,
} from "@/api/system/classify";
import { getToken } from "@/utils/auth";
import { deptNameList } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
    name: "diseaseList",
    dicts: ["sys_normal_disable", "sys_manage_diseases"],
    components: { department, departTag, platformTemp },
    data() {
        return {
            platformTempDialogVisible: false,
            platformTitle: '平台模板-专病',
            stainArr: [{ value: 0, label: '否' }, { value: 1, label: '是' },],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            diseaseClassifyName: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 专病表格数据
            classifyList: null,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 是否修改
            inputDisabled: false,
            // 表单参数
            // form: {},
            form: {
                createBy: undefined,
                createTime: undefined,
                delFlag: undefined,
                diseaseClassifyId: undefined,
                diseaseClassifyName: undefined,
                diseaseSerialization: undefined,
                diseaseType: undefined,
                params: {},
                remark: undefined,
                searchValue: undefined,
                status: undefined,
                updateBy: undefined,
                updateTime: undefined,
                deptId: undefined,
                hospitalId: undefined,
                platformType: 0
            },
            deptNameLists: [],
            mform: { fx: '', fq: '', },
            fxz: [],
            fqz: [],
            // 专病导入参数
            upload: {
                // 是否显示弹出层（专病导入）
                open: false,
                // 弹出层标题（专病导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的专病数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/system/user/importData",
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                diseaseClassifyName: undefined,
                hospitalId: undefined,
                deptId: undefined,
                // diseaseClassifyName: undefined,
                status: undefined,
            },
            // 表单校验
            rules: {
                diseaseClassifyName: [
                    {
                        required: true,
                        message: "专病名称不能为空",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "科室必选",
                        trigger: "blur",
                    },
                ],
                // diseaseClassifyName: [
                //     {
                //         required: true,
                //         message: "专病分类不能为空",
                //         trigger: "blur",
                //     },
                // ],
            },
            //是否数组
            yesOrNoArr: ["是", "否"],
            tableData1: [
                {
                    name: '毛细血管型',
                }, {
                    name: '真皮型',
                }, {
                    name: '表皮型',
                },
            ],
            tableData2: [
                {
                    name: '活动期',
                }, {
                    name: '静止期',
                },
            ]
        };
    },
    watch: {},
    created() {
       // this.getdeptNameList();
    },
    computed: {
        ...mapGetters(["isPlatform", "deptId", "hospital"]),
        isAdmin() {
            return this.$store.state.user.name === 'admin' ? true : false
        }
    },
    methods: {
        closeplatformTempDialogVisible() {
            this.platformTempDialogVisible = false
        },
        refreshData(data) {
            this.queryParams.pageNum = 1;
            this.queryParams.hospitalId = data.hospitalId
            //this.queryParams.deptId = data.deptId
            this.getdeptNameList();
        },
        changedepatData(data) {
            if (data && data.length > 0) {
                this.form.deptId = data[0].deptId
                this.form.hospitalId = data[0].parentId==100?data[0].deptId:data[0].parentId
            } else {
                this.form.deptId = undefined
                this.form.hospitalId = undefined
            }
        },
        // 回显医院及门诊
        getdeptNameList() {
            deptNameList().then((response) => {
                this.deptNameLists = response.data;
                this.getList();
            });
        },
        addFX() {
            if (this.mform.fx === '') {
                this.$message.warning('请输入分型值再添加')
            } else if (this.fxz.indexOf(this.mform.fx) > -1) {
                this.$message.warning('此分型值已存在请勿重复添加')
            } else {
                this.fxz.push(this.mform.fx)
                this.mform.fx = ''
            }
        },
        fxzHandleClose(tag) {
            this.fxz.splice(this.fxz.indexOf(tag), 1);
        },
        addFQ() {
            if (this.mform.fq === '') {
                this.$message.warning('请输入分期值再添加')
            } else if (this.fqz.indexOf(this.mform.fq) > -1) {
                this.$message.warning('此分期值已存在请勿重复添加')
            } else {
                this.fqz.push(this.mform.fq)
                this.mform.fq = ''
            }
        },
        fqzHandleClose(tag) {
            this.fqz.splice(this.fqz.indexOf(tag), 1);
        },
        /** id转化成对应的文字 */
        matchDict: function (key, id) {
            let _this = this;
            const result = _this.dict.type[key];
            let textValue = "";
            result.forEach((item) => {
                if (item.raw.dictValue == id) {
                    textValue = item.raw.dictLabel;
                }
            });
            return textValue;
        },
        /** 查询专病列表 */
        getList() {
            this.loading = true;
            listClassify(
                this.addDateRange(this.queryParams, this.dateRange)
            ).then((response) => {
                this.classifyList = response.rows;
                this.classifyList.forEach((item, index) => {
                    item.diseaseType = JSON.parse(item.diseaseType).join('、')
                    item.diseaseSerialization = JSON.parse(item.diseaseSerialization).join('、')
                })
                console.log('this.classifyList', this.classifyList)
                this.total = response.total;
                this.loading = false;
            });
        },
        // 专病状态修改
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "停用";
            this.$modal
                .confirm(
                    "确认要" +
                    text +
                    "专病分类为" +
                    row.diseaseClassifyName +
                    "的数据项吗?"
                )
                .then(function () {
                    return changeClassifyStatus(
                        row.diseaseClassifyId,
                        row.status
                    );
                })
                .then(() => {
                    this.$modal.msgSuccess(text + "成功");
                })
                .catch(function () {
                    row.status = row.status === "0" ? "1" : "0";
                });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.mform = { fx: '', fq: '', }
            this.reset();
        },

        // 表单重置
        reset() {
            this.form = {
                userId: undefined,
                deptId: undefined,
                userName: undefined,
                nickName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: "0",
                remark: undefined,
                platformType: 0
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.diseaseClassifyId);
            this.diseaseClassifyName = selection.map((item) => item.diseaseClassifyName);
            this.single = selection.length != 1;
            this.multiple = selection.length != 1;
            // this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.inputDisabled = false
            this.open = true;
            this.title = "新增专病";
            this.fxz = []
            this.fqz = []

        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.inputDisabled = true
            console.log('handleUpdate', row)
            // this.fxz = JSON.parse(row.diseaseType.split);
            // this.fqz = JSON.parse(row.diseaseSerialization);
            if (row.diseaseType == '') {
                this.fxz = []
            } else {
                this.fxz = row.diseaseType.split('、');
            }
            if (row.diseaseSerialization == '') {
                this.fqz = []
            } else {
                this.fqz = row.diseaseSerialization.split('、');
            }

            console.log(this.fxz, this.fxz)
            const diseaseClassifyId = row.diseaseClassifyId || this.ids;
            getClassify(diseaseClassifyId).then((response) => {
                let data = response.data;
                this.form = response.data;
                if (data.platformType == undefined || data.platformType == null || data.platformType == '') {
                    this.form.platformType = 0
                }
                this.open = true;
                this.title = "修改专病";
            });
        },
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                inputPattern: /^.{5,20}$/,
                inputErrorMessage: "专病密码长度必须介于 5 和 20 之间",
            })
                .then(({ value }) => {
                    resetUserPwd(row.userId, value).then((response) => {
                        this.$modal.msgSuccess("修改成功，新密码是：" + value);
                    });
                })
                .catch(() => { });
        },

        /** 提交按钮 */
        submitForm: function () {
            // console.log('this.fxz',this.fxz)
            // console.log('this.fqz',this.fqz)
            this.form.diseaseType = JSON.stringify(this.fxz)
            this.form.diseaseSerialization = JSON.stringify(this.fqz)
            // console.log('this.fxz',this.form.diseaseType)
            // console.log('this.fqz',this.form.diseaseSerialization)
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.diseaseClassifyId != undefined) {
                        updateClassify(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.mform = { fx: '', fq: '', }
                            this.getList();
                        });
                    } else {
                        addClassify(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.mform = { fx: '', fq: '', }
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            console.log('handleDelete', this.diseaseClassifyName)
            const diseaseClassifyName = row.diseaseClassifyName || this.diseaseClassifyName
            const classifyIds = row.diseaseClassifyId || this.ids;
            this.$modal
                .confirm(
                    '是否确认删除专病名称为"' +
                    diseaseClassifyName +
                    '"的数据项？'
                )
                .then(function () {
                    return delClassify(classifyIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "system/user/export",
                {
                    ...this.queryParams,
                },
                `user_${new Date().getTime()}.xlsx`
            );
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "专病导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                "system/user/importTemplate",
                {},
                `user_template_${new Date().getTime()}.xlsx`
            );
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                response.msg +
                "</div>",
                "导入结果",
                { dangerouslyUseHTMLString: true }
            );
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
    },
};
</script>
<style scoped>
.el-tag {
    margin-right: 15px;
}
</style>
